﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;

namespace BaseSimpleAPI
{
    /// <summary>
    /// 网络调用上下文
    /// </summary>
    public class TagHelper
    {
        private TagHelper() { }

        /// <summary>
        /// 我的小布兜
        /// </summary>
        private ConcurrentDictionary<string, object> _Tag = new ConcurrentDictionary<string, object>();

        /// <summary>
        /// 当前对象
        /// </summary>
        public static TagHelper Current
        {
            get { return (TagHelper)_NetCallContext.Value; }
        }

        private static ThreadLocal<TagHelper> _NetCallContext = new ThreadLocal<TagHelper>();

        /// <summary>
        /// 新的实例
        /// </summary>
        /// <returns></returns>
        public static TagHelper NewCurrent()
        {
            _NetCallContext.Value = new TagHelper();
            return _NetCallContext.Value;
        }

        private string GetCacheKey<T>(object key)
        {
            return string.Format("{0}::{1}", typeof(T).FullName, key ?? "Default");
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="key"></param>
        public void SetData<T>(T t, object key = null)
        {
            _Tag[GetCacheKey<T>(key)] = t;
        }

        /// <summary>
        /// 尝试获取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetData<T>(object key = null)
        {
            var cache_key = GetCacheKey<T>(key);

            if (_Tag.TryGetValue(cache_key, out object obj) && obj is T)
                return (T)obj;

            return default(T);
        }

        /// <summary>
        /// 判断是否包含此数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool ContainData<T>(object key = null)
        {
            var cache_key = GetCacheKey<T>(key);
            return _Tag.ContainsKey(cache_key);
        }
    }
}
